﻿@using System.Net.Http.Headers
@using System.IO.Compression
@using System.Xml.Linq
@using Tool.Models
@using Tool.Services
@using Tool.Utils
@inject IDialogService dialogService
@inject CustomerService customerService
@inject EvdService evdService
@inject ISnackbar Snackbar
@inject IJSRuntime JavaScript;
@inject LoginService loginService
<MudGrid>
	<MudItem xs="2">
		<MudTextField @bind-Value="EvdNo" Label="报销单号/申请单号" Variant="Variant.Text" Adornment="Adornment.Start"
					  AdornmentIcon="@Icons.Material.Filled.LockPerson" Clearable="true" />
	</MudItem>

	<MudItem xs="2" Class="align-content-center">
		<MudButton Class="align-self-center" FullWidth="true" Disabled="@_processing" OnClick="GetEvds" Variant="Variant.Filled" Color="Color.Primary">
			@if (_processing)
			{
				<MudProgressCircular Class="ms-n1" Indeterminate="true" />
				<MudText Class="ms-2">Processing</MudText>
			}
			else
			{
				<MudText>获取Evd信息</MudText>
			}
		</MudButton>
	</MudItem>
	<MudItem xs="2" Class="align-content-center">
		<MudButton Class="align-self-center" FullWidth="true" Disabled="@_downloadingEvd" OnClick="DownloadEvds" Variant="Variant.Filled" Color="Color.Primary">
			@if (_downloadingEvd)
			{
				<MudProgressCircular Class="ms-n1" Indeterminate="true" />
				<MudText Class="ms-2">Processing</MudText>
			}
			else
			{
				<MudText>下载Evd文件</MudText>
			}
		</MudButton>
	</MudItem>
	<MudItem xs="2" Class="align-content-center">
		<MudButton Class="align-self-center" FullWidth="true" Disabled="@_downloadingPay" OnClick="DownloadPayFiles" Variant="Variant.Filled" Color="Color.Primary">
			@if (_downloadingPay)
			{
				<MudProgressCircular Class="ms-n1" Indeterminate="true" />
				<MudText Class="ms-2">Processing</MudText>
			}
			else
			{
				<MudText>下载Pay文件</MudText>
			}
		</MudButton>
	</MudItem>
	<MudItem xs="2" Class="align-content-center">
		<MudButton Class="align-self-center" FullWidth="true" OnClick="ReSendEvd" Variant="Variant.Filled" Color="Color.Primary">
			<MudText>推送/删除</MudText>
		</MudButton>
	</MudItem>
	<MudItem xs="2" Class="align-content-center">
		<MudButton Class="align-self-center" FullWidth="true" OnClick="ClearResults" Variant="Variant.Filled" Color="Color.Primary">
			<MudText>清空</MudText>
		</MudButton>
	</MudItem>
	<MudItem xs="12">
		<MudTable Items="@_evds" @bind-SelectedItems="_selectedEvds" Dense="true" Hover="true" Bordered="true" Striped="true" MultiSelection="true" CustomHeader="true" CustomFooter="true">
			<ToolBarContent>
				<MudText Typo="Typo.h6">evd信息(总数：@_totalCount)</MudText>
				<MudSpacer />
			</ToolBarContent>
			<HeaderContent>
				<MudTHeadRow Checkable="true">
					<MudTh><MudTableSortLabel SortBy="new Func<EvdDto, object>(x => x.ReimApplyOrderNo)">ReimApplyOrderNo</MudTableSortLabel></MudTh>
					<MudTh><MudTableSortLabel SortBy="new Func<EvdDto, object>(x => x.BatchNo)">BatchNo</MudTableSortLabel></MudTh>
					<MudTh>UserCode</MudTh>
					<MudTh>PayUrl</MudTh>
					<MudTh>EvdUrl</MudTh>
					<MudTh>Action</MudTh>
				</MudTHeadRow>
			</HeaderContent>
			<RowTemplate>
				<MudTd DataLabel="ReimApplyOrderNo">@context.ReimApplyOrderNo</MudTd>
				<MudTd DataLabel="BatchNo">@context.BatchNo</MudTd>
				<MudTd DataLabel="UserCode">@context.UserCode</MudTd>
				<MudTd DataLabel="PayUrl">@context.PayUrl</MudTd>
				<MudTd DataLabel="EvdUrl">@context.EvdUrl</MudTd>
				<MudTd DataLabel="Action"><MudButton OnClick="() => ShowEvd(context.EvdUrl)" Variant="Variant.Filled" Color="Color.Info">查看</MudButton></MudTd>
			</RowTemplate>
			<FooterContent>
				<MudTFootRow Checkable="true">
					<MudTd colspan="5">Selected: @_selectedEvds?.Count</MudTd>
				</MudTFootRow>
			</FooterContent>
			<PagerContent>
				<MudTablePager />
			</PagerContent>
		</MudTable>
	</MudItem>
</MudGrid>

@code {

	private bool _processing = false;
	private bool _downloadingEvd = false;
	private bool _downloadingPay = false;

	private List<EvdDto> _evds = new List<EvdDto>();
	private HashSet<EvdDto> _selectedEvds = new HashSet<EvdDto>();
	public int _totalCount = 0;


	[Parameter]
	public string EvdNo { get; set; }
	[Parameter]
	public string SelectedSite { get; set; }
	[Parameter]
	public HttpResponseHeaders ResponseHeaders { get; set; }
	[Parameter]
	public string GroupName { get; set; } = string.Empty;
	[Parameter]
	public string UserCode { get; set; } = string.Empty;
	[Parameter]
	public string AdmdivCode { get; set; } = string.Empty;
	[Parameter]
	public string CompanyCode { get; set; } = string.Empty;

	private string evdType = "BX"; // 默认报销单

	private async Task GetEvds()
	{
		_processing = true;

		try
		{
			if (string.IsNullOrWhiteSpace(EvdNo) || EvdNo.Length < 14)
			{
				await dialogService.ShowMessageBox("错误", "请输入正确的报销单号，长度至少为14位。");
				return;
			}
			if (UserCode.IsBlank())
			{
				await GetCustomer();
			}
			var tableCount = SelectedSite == "sh" ? 128 : 512;
			if (GroupName == "企业")
			{
				tableCount = 16;
			}
			var tableName = TableHelper.GetTableNameNew("reim_order_manage", UserCode, tableCount);
			
			var reimSql = string.Empty;
			var totalSql = string.Empty;
			if (EvdNo.StartsWith("BX", true, System.Globalization.CultureInfo.InvariantCulture))
			{
				evdType = "BX";
				reimSql = $"select user_code, batch_no,reim_apply_order_no,pay_url,evd_url from {tableName} where user_code='{UserCode}' and batch_no like '{EvdNo}%'";
				totalSql = $"select count(1) from {tableName} where user_code='{UserCode}' and batch_no like '{EvdNo}%'";
			}
			else if (EvdNo.StartsWith("LS", true, System.Globalization.CultureInfo.InvariantCulture))
			{
				evdType = "BX";
				reimSql = $"select user_code, batch_no,reim_apply_order_no,pay_url,evd_url from {tableName} where user_code='{UserCode}' and reim_apply_order_no like '{EvdNo}%'";
				totalSql = $"select count(1) from {tableName} where user_code='{UserCode}' and reim_apply_order_no like '{EvdNo}%'";
			}
			else if (EvdNo.StartsWith("FB", true, System.Globalization.CultureInfo.InvariantCulture))
			{
				reimSql = $"select user_code, reim_approval_no as batch_no,reim_apply_order_no,pay_file_url pay_url,evd_file_url evd_url from office_supply_reim_manage where user_code='{UserCode}' and reim_approval_no like '{EvdNo}%'";
				totalSql = $"select count(1) from office_supply_reim_manage where user_code='{UserCode}' and reim_approval_no like '{EvdNo}%'";
				evdType = "FB";
			}

			if (SelectedSite != "zwy")
			{
				ResponseHeaders = await loginService.Login(SelectedSite);
			}

			_evds = await evdService.GetEvds(reimSql, SelectedSite, ResponseHeaders, GroupName, evdType);
			if (_evds == null || _evds.Count == 0)
			{
				Snackbar.Add("未查询到evd记录", Severity.Error);
			}
			_totalCount = await evdService.GetEvdsCount(totalSql, SelectedSite, ResponseHeaders, GroupName, evdType);
		}
		catch (Exception ex)
		{
			Snackbar.Add($"发生异常：{ex.Message}", Severity.Error);
		}
		finally
		{
			_processing = false;
		}
	}

	private async Task GetCustomer()
	{
		var finAdmdivCode = string.Empty;
		var companyCode = string.Empty;
		if (EvdNo.Length == 25 || EvdNo.Length == 17)
		{
			finAdmdivCode = EvdNo.Substring(2, 9);
			companyCode = EvdNo.Substring(11, 6);
		}
		else if (EvdNo.Length == 28 || EvdNo.Length == 20)
		{
			finAdmdivCode = EvdNo.Substring(2, 9);
			companyCode = EvdNo.Substring(11, 9);
		}
		else
		{
			finAdmdivCode = EvdNo.Substring(2, 6);
			companyCode = EvdNo.Substring(8, 6);
		}
		int tryCount = 2;
		while (tryCount > 0)
		{
			var centerSql = $"select id, user_code, customer_name, company_code, admdiv_code, admdiv_name,group_id, status from customer_center where admdiv_code = '{finAdmdivCode}' and company_code='{companyCode}'";
			var centerCustomers = await customerService.GetCustomers(centerSql, SelectedSite, ResponseHeaders);

			var sql = $"select a.id, a.user_code, a.customer_name, a.company_code, a.admdiv_code, a.admdiv_name,b.fin_admdiv_code from customer_base a inner join customer_extra b on a.user_code=b.user_code where fin_admdiv_code = '{finAdmdivCode}' and a.company_code ='{companyCode}'";
			GroupName = centerCustomers?.FirstOrDefault()?.GroupName;
			var customers = await customerService.GetLocalCustomers(sql, SelectedSite, ResponseHeaders, GroupName);

			if (customers != null && customers.Count > 0)
			{
				UserCode = customers.FirstOrDefault().UserCode;
				tryCount = 0;
			}
			else
			{
				if (EvdNo.Length == 25 || EvdNo.Length == 17)
				{
					finAdmdivCode = EvdNo.Substring(2, 6);
					companyCode = EvdNo.Substring(8, 9);
					tryCount--;
				}
				else
				{
					tryCount = 0;
					Snackbar.Add("解析单号失败", Severity.Error);
				}
			}
		}
	}

	private async Task DownloadEvds()
	{
		_downloadingEvd = true;
		try
		{
			foreach (var item in _selectedEvds)
			{
				await DownloadFile(item.EvdUrl, item.BatchNo, "evd");
			}
		}
		catch (Exception ex)
		{
			Snackbar.Add($"下载文件异常：{ex.Message}", Severity.Error);
		}
		finally
		{
			_downloadingEvd = false;
		}
	}

	private async Task DownloadPayFiles()
	{
		_downloadingPay = true;
		try
		{
			foreach (var item in _selectedEvds)
			{
				await DownloadFile(item.PayUrl, item.BatchNo, "pay");
			}
		}
		catch (Exception ex)
		{
			Snackbar.Add($"下载文件异常：{ex.Message}", Severity.Error);
		}
		finally
		{
			_downloadingPay = false;
		}
	}

	private async Task DownloadFile(string fileUrl, string reimNo, string extension)
	{

		// 下载文件
		// 1. 提取 fileId (去掉第一个 '/' 之前的部分)
		string fileId = fileUrl.Substring(fileUrl.IndexOf("/") + 1);

		// 2. 获取当前时间戳 (秒)
		int ts = (int)(DateTimeOffset.UtcNow.ToUnixTimeSeconds());

		// 3. 生成 token
		string token = FileHelper.GetToken(fileId, ts, "SFqdFASTDFS#@!$%^");

		// 4. 构造带参数的 URL
		string queryString = $"token={token}&ts={ts}";
		string fullFileUrl = $"{fileUrl}?{queryString}";

		// 5. 构造完整的下载 URL
		// 注意：原始 Java 代码中 URL 后面有空格，这里已修正
		var completeUrl = $"{FileHelper.GetFileHost(SelectedSite, GroupName)}/{fullFileUrl}";

		byte[] bytes = await HttpUtil.DownloadBytesAsync(completeUrl);
		// using (MemoryStream ms = new MemoryStream(bytes))
		// {
		//     using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Read))
		//     {
		//         string comment = archive.Comment;
		//         foreach (ZipArchiveEntry entry in archive.Entries)
		//         {
		//             Console.WriteLine($"文件名: {entry.FullName}, 大小: {entry.Length} 字节");
		//             读取content.xml文件中的  ReimbursementFormNo 这个节点的值
		//             if (entry.FullName.EndsWith("content.xml", StringComparison.OrdinalIgnoreCase))
		//             {
		//                 using (StreamReader reader = new StreamReader(entry.Open()))
		//                 {
		//                     string content = reader.ReadToEnd();
		//                     这里可以解析 XML 内容，提取 ReimbursementFormNo 节点的值

		//                     try
		//                     {
		//                         var xdoc = XDocument.Parse(content);
		//                         假设节点路径为 <ReimbursementFormNo>xxx</ReimbursementFormNo>
		//                         var node = xdoc.Descendants("ReimbursementFormNo").FirstOrDefault();
		//                         if (node != null)
		//                         {
		//                             reimNo = node.Value;
		//                             Console.WriteLine($"ReimbursementFormNo: {reimNo}");
		//                         }
		//                         else
		//                         {
		//                             Console.WriteLine("未找到 ReimbursementFormNo 节点");
		//                         }
		//                     }
		//                     catch (Exception ex)
		//                     {
		//                         Console.WriteLine($"解析 XML 失败: {ex.Message}");
		//                     }
		//                 }
		//             }
		//         }
		//         Console.WriteLine(comment);
		//     }
		// }
		await JavaScript.InvokeVoidAsync("downloadFileFromBytes", bytes, $"{reimNo}.{extension}", "application/zip");
	}

	private async Task ShowEvd(string evdUrl)
	{
		var options = new DialogOptions
		{
			FullWidth = true,
			MaxWidth = MaxWidth.Medium,
			CloseOnEscapeKey = true
			// FullScreen = true
		};
		await dialogService.ShowAsync<ShowEvdDetails>
	("查看EVD", new DialogParameters { { "EvdUrl", evdUrl }, { "SelectedSite", SelectedSite } }, options);
	}

	private async Task ReSendEvd()
	{
		if (_selectedEvds.Count == 0)
		{
			Snackbar.Add("请选择需要重新推送的EVD文件", Severity.Error);
			return;
		}

		var options = new DialogOptions
		{
			FullWidth = true,
			MaxWidth = MaxWidth.Medium,
			CloseOnEscapeKey = true,
			Position = DialogPosition.TopCenter
			// FullScreen = true
		};
		await dialogService.ShowAsync<SyncHistoryDataDialog>("同步历史数据", new DialogParameters
		{
			{ "SendType", 2 },
			{ "SelectedEvds", _selectedEvds.ToList() }, 
			{ "UserCode", _selectedEvds.FirstOrDefault()?.UserCode }, 
			{ "GroupName", GroupName } ,
			{ "EvdType", evdType},
			{ "CompanyCode", CompanyCode},
			{ "AdmdivCode", AdmdivCode},
		}, options);
	}

	private void ClearResults()
	{
		_evds.Clear();
		_selectedEvds.Clear();
		_totalCount = 0;
	}
}
